import axios from 'axios'
import { ElMessage } from 'element-plus'
const baseURL = import.meta.env.VITE_BASE_URL

const service = axios.create({
  baseURL: baseURL,
  timeout: 60 * 1000
})

//响应拦截器
service.interceptors.response.use(
  (response) => {
    if (response.status == 200 && response.request.responseType === 'blob') {
      return response
    }
    const res = response.data
    if (res.code === 200) {
      return res
    } else {

      showError({ code: res.code, message: res.message })
      return Promise.reject(res)
    }
  },
  (error) => {
    showError(error)
    return Promise.reject(error)
  }
)

// 错误处理
function showError(error) {
    ElMessage({
        message: error?.response?.data?.message || error.msg || error.message || '服务异常',
        type: 'error',
        duration: 3 * 1000
    })
}

export default service